SOLID SRP Example in Java

Problem Statement:

Consider a class Employee that handles both employee information and file operations:

        
class Employee {
    private String name;
    private String id;

    // ... other properties and methods ...

    public void saveToFile() {
        // logic to save employee details to a file
    }

    public void loadFromFile() {
        // logic to load employee details from a file
    }
}
        
    

This violates SRP as the Employee class has multiple reasons to change: one for employee information and another for file operations.

Solution - Applying SRP:

Separate concerns by creating a separate class for file operations:

        
class Employee {
    private String name;
    private String id;

    // ... other properties and methods ...
}

class EmployeeFileHandler {
    public void saveToFile(Employee employee) {
        // logic to save employee details to a file
    }

    public Employee loadFromFile(String employeeId) {
        // logic to load employee details from a file
        // return loaded employee object
    }
}
        
    

Now, the Employee class focuses solely on employee-related functionality, adhering to the Single Responsibility Principle.

Benefits: